<template>
  <div class="car-store-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="门店名称">
          <el-input v-model="searchForm.storeName" placeholder="请输入门店名称" clearable />
        </el-form-item>

        <el-form-item label="店长/店员姓名">
          <el-input v-model="searchForm.staffName" placeholder="请输入店长/店员姓名" clearable />
        </el-form-item>

        <el-form-item label="门店类型">
          <el-select v-model="searchForm.storeType" style="width: 100px;" placeholder="请选择门店类型" clearable>
            <el-option label="直营店" value="直营店" />
            <el-option label="加盟店" value="加盟店" />
          </el-select>
        </el-form-item>

        <el-form-item label="营业状态">
          <el-select v-model="searchForm.businessStatus" style="width: 100px;" placeholder="请选择营业状态" clearable>
            <el-option label="营业中" value="营业中" />
            <el-option label="停业中" value="停业中" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="success" @click="handleAddStore">新增门店</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 视图切换区域 -->
    <div class="view-toggle">
      <el-radio-group v-model="viewType">
        <el-radio-button label="card">卡片视图</el-radio-button>
        <el-radio-button label="list">列表视图</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 卡片视图 -->
      <div v-if="viewType === 'card'" class="card-view">
        <div class="card-grid">
          <el-card
              v-for="store in storeList"
              :key="store.id"
              :class="store.businessStatus == '营业中' ? 'open-store-card' : 'closed-store-card'"
              class="store-card">

            <!-- 卡片顶部：门店名称和营业状态 -->
            <div class="card-header">
              <div class="store-name">{{ store.storeName }}</div>
              <div class="business-status">
                <el-tag :type="store.businessStatus === '营业中' ? 'success' : 'danger'">
                  {{ store.businessStatus === '营业中' ? '营业中' : '停业中' }}
                </el-tag>
              </div>
            </div>

            <!-- 卡片中间：门店基本信息 -->
            <div class="card-content">
              <div class="info-row">
                <span class="info-label">店长：</span>
                <span class="info-value">{{ store.storeManager?.staffName??''}}</span>
              </div>
              <div class="info-row">
                <span class="info-label">电话：</span>
                <span class="info-value">{{ store.servicePhone }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">地址：</span>
                <span class="info-value">{{ store.defaultAddress?.defaultAddressData??'' }}</span>
              </div>

              <div class="stats-row">
                <div class="stat-item">
                  <div class="stat-value">{{ store.monthSale?.monthlyRevenue ?? 0 }}元</div>
                  <div class="stat-label">当月营业</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ store.monthSale?.goodsCount??0 }}</div>
                  <div class="stat-label">在售商品</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ store.monthSale?.serviceCount??0 }}</div>
                  <div class="stat-label">服务数量</div>
                </div>
              </div>
            </div>

            <!-- 卡片底部：操作按钮 -->
            <div class="card-footer">
              <el-button type="text" size="small" @click="handleViewGoods(store.id)">在售商品</el-button>
              <el-button type="text" size="small" @click="handleViewPersonnel(store.id)">员工管理</el-button>
<!--              <el-button type="text" size="small" @click="handleEditStore(store.id)">门店编辑</el-button>-->
              <el-button
                  type="text"
                  size="small"
                  :class="store.businessStatus == '营业中' ? 'btn-close' : 'btn-open'"
                  @click="store.businessStatus == '营业中' ? handleCloseStore(store) : handleOpenStore(store)">
                {{ store.businessStatus === '营业中' ? '门店歇业' : '门店开业' }}
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[5, 10, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="list-view">
        <el-table :data="storeList" stripe>
          <!-- 修改后：自定义全局序号 -->
          <el-table-column label="序号" width="80">
            <template #default="scope">
              <!-- 计算逻辑：(当前页-1)*每页条数 + 页内索引 + 1 -->
              {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="id" label="门店ID" />
          <el-table-column prop="storeName" label="门店名称" />
          <el-table-column prop="storeManager.staffName" label="店长名称" />
          <el-table-column prop="servicePhone" label="联系电话" />

          <el-table-column prop="businessHours" label="营业时间" />
          <el-table-column prop="storeType" label="门店类型">
            <template #default="scope">
              {{ scope.row.storeType == '直营店' ? '直营店' : '加盟店' }}
            </template>
          </el-table-column>
          <el-table-column prop="stationCount" label="工位数量" />
          <el-table-column prop="businessStatus" label="营业状态">
            <template #default="scope">
              <el-tag :type="scope.row.businessStatus == '营业中' ? 'success' : 'danger'">
                {{ scope.row.businessStatus == '营业中' ? '营业中' : '停业中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="地图位置">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleViewMap(scope.row)">查看地图</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleEditStore(scope.row.id)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDeleteStore(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[5, 10, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 确认对话框 - 歇业 -->
    <el-dialog :visible.sync="closeDialogVisible" title="确认歇业">
      <template #content>
        <p>{{ closeDialogMessage }}</p>
      </template>
      <template #footer>
        <el-button @click="closeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCloseStore">确认</el-button>
      </template>
    </el-dialog>

    <!-- 确认对话框 - 开业 -->
    <el-dialog :visible.sync="openDialogVisible" title="确认开业">
      <template #content>
        <p>{{ openDialogMessage }}</p>
      </template>
      <template #footer>
        <el-button @click="openDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmOpenStore">确认</el-button>
      </template>
    </el-dialog>

    <!-- 确认对话框 - 删除门店 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="确认删除">
      <template #content>
        <p>{{ deleteDialogMessage }}</p>
      </template>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDeleteStore">确认</el-button>
      </template>
    </el-dialog>

    <!-- 地图弹窗 -->
    <el-dialog :visible.sync="mapDialogVisible" title="门店位置地图" width="70%">
      <template #content>
        <div class="map-container" id="mapContainer">
          <!-- 这里会显示地图，实际项目中需要集成地图API -->
          <div class="map-placeholder">
            <p>地图位置: {{ selectedStore?.address || '加载中...' }}</p>
            <img src="https://picsum.photos/800/400?random=map" alt="地图示例" class="map-image">
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="mapDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch, onActivated} from 'vue'
import { useRouter } from 'vue-router'
import axios from "axios";
import {ElMessage} from "element-plus";

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  storeName: '',
  staffName: '',
  storeType: '',
  businessStatus: ''
})

// 视图类型：card 或 list
const viewType = ref('card')

// 分页相关
const pageNum = ref(1)
const pageSize = ref(4)
const total = ref(0)
const storeList = ref([
  {
    "id": 1,
    "storeName": "极速汽车服务中心",
    "storeType": "直营店",
    "servicePhone": "17899999999",
    "businessHours": "09:00-18:00",
    "businessStatus": "营业中",
    "businessLicense": "110105123456789",
    "stationCount": 50,
    "managerId": 401,
    "storeManager": {
      "id": 401,
      "staffName": "李店长",
      "phone": "13811111111"
    },
    "monthSale": {
      "storeId": 1,
      "monthlyRevenue": 200,
      "goodsCount": 1,
      "serviceCount": 1
    },
    "defaultAddress": {
      "storeId": 1,
      "defaultAddressId": 327798786,
      "defaultAddressData": "广东省\t广州市\t市辖区\t荔湾区盘虬街道100号"
    }
  },
])

// 对话框相关
const closeDialogVisible = ref(false)
const closeDialogMessage = ref('')
const storeToClose = ref(null)

const openDialogVisible = ref(false)
const openDialogMessage = ref('')
const storeToOpen = ref(null)

const deleteDialogVisible = ref(false)
const deleteDialogMessage = ref('')
const storeToDelete = ref(null)

const mapDialogVisible = ref(false)
const selectedStore = ref(null)

//获取门店列表
const getStoreList= ()=>{
  axios.post(`/carcenter-service-store/store-info/getStoreList/${pageNum.value}/${pageSize.value}`,searchForm ).then(
      resp=>{
        storeList.value = resp.data.data.list;
        total.value = resp.data.data.total;
      }
  ).catch(error => {
    console.error('Error fetching store list:', error);
  });

}

// 页面加载时获取门店数据
onMounted(() => {
  getStoreList();

})

// 错误：getStoreList() 会立即执行，且返回值是 undefined
//onActivated(getStoreList())

// 正确：传入函数本身，由 onActivated 在合适时机调用
onActivated(getStoreList)



// 视图类型变化时的处理（添加watch监听）
watch(viewType, (newType) => {
  // 切换视图时重置到第一页，避免不同视图的分页状态冲突
  pageNum.value = 1;
  getStoreList();
});


// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  getStoreList()
}

const handleCurrentChange = (newPage) => {
  pageNum.value = newPage
  getStoreList()
}

// 搜索按钮点击事件
const handleSearch = () => {
  pageNum.value = 1 // 重置到第一页
  getStoreList()
}

// 新增门店
const handleAddStore = () => {
  router.push({ name: 'StoreNew' })
}

// 查看商品
const handleViewGoods = (storeId) => {
  router.push({ name: 'StoreGoods', params: { storeId } })
}

// 查看员工
const handleViewPersonnel = (storeId) => {
  router.push({ name: 'StorePersonnel', params: { storeId } })
}

// 编辑门店
const handleEditStore = (storeId) => {
  router.push({
    name: 'StoreEdit', // 使用命名路由
    params: {
      storeId,           // 传递 storeId
    }
  })
}


const confirmCloseStore = () => {
  if (storeToClose.value) {
    // 直接调用API更新状态，不手动修改storeList
    axios.post(`/carcenter-service-store/store-info/close/${storeToClose.value.id}`)
        .then(() => {
          getStoreList() // 重新加载数据
          closeDialogVisible.value = false
          storeToClose.value = null
          ElMessage({ type: 'success', message: '门店已成功歇业' })
        })
        .catch(error => {
          console.error('歇业失败:', error)
          ElMessage({ type: 'error', message: '歇业失败，请重试' })
        })
  }
}

// 同理，修改confirmOpenStore方法
const confirmOpenStore = () => {
  if (storeToOpen.value) {
    axios.post(`/carcenter-service-store/store-info/open/${storeToOpen.value.id}`)
        .then(() => {
          getStoreList()
          openDialogVisible.value = false
          storeToOpen.value = null
          ElMessage({ type: 'success', message: '门店已成功开业' })
        })
        .catch(error => {
          console.error('开业失败:', error)
          ElMessage({ type: 'error', message: '开业失败，请重试' })
        })
  }
}



// 歇业门店
const handleCloseStore = (store) => {
  storeToClose.value = store
  closeDialogMessage.value = `歇业后用户端将看不到此门店，请问是否将 ${store.storeName} 设置为歇业？`
  closeDialogVisible.value = true
}



// 开业门店
const handleOpenStore = (store) => {
  storeToOpen.value = store
  openDialogMessage.value = `开业后用户端将显示此门店，请问是否将 ${store.storeName} 设置为开业？`
  openDialogVisible.value = true
}


// 删除门店
const handleDeleteStore = (store) => {
  storeToDelete.value = store
  deleteDialogMessage.value = `请问是否将 ${store.storeName} 删除？`
  deleteDialogVisible.value = true
}

// 确认删除门店
const confirmDeleteStore = () => {
  if (storeToDelete.value) {
    // 模拟API请求
    setTimeout(() => {
      // 实际项目中应该发送请求到API
      const index = storeList.findIndex(s => s.id === storeToDelete.value.id)
      if (index !== -1) {
        storeList.splice(index, 1)
      }

      getStoreList()
      deleteDialogVisible.value = false
      storeToDelete.value = null

      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '门店已成功删除'
      })
    }, 300)
  }
}

// 查看地图
const handleViewMap = (store) => {
  selectedStore.value = store
  mapDialogVisible.value = true

  // 在实际项目中，这里应该初始化地图
  initMap()
}

// 初始化地图（示例函数）
const initMap = () => {
  // 实际项目中，这里应该集成地图API，如高德地图、百度地图等
  // 以下是示例代码，展示如何使用地图API
  // 注意：需要在项目中引入相应的地图SDK
  /*
  if (selectedStore.value && typeof AMap !== 'undefined') {
    const map = new AMap.Map('mapContainer', {
      zoom: 16,
      center: [selectedStore.value.longitude, selectedStore.value.latitude]
    })

    new AMap.Marker({
      position: [selectedStore.value.longitude, selectedStore.value.latitude],
      map: map
    })
  }
  */
}
</script>

<style scoped>
.car-store-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.view-toggle {
  margin-bottom: 20px;
}

.content-area {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-view {
  padding: 10px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.store-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.store-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.open-store-card {
  border: 1px solid #e6e6e6;
}

.closed-store-card {
  border: 1px solid #e6e6e6;
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.store-name {
  font-size: 18px;
  font-weight: bold;
}

.card-content {
  padding: 15px;
}

.info-row {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.info-label {
  color: #8c8c8c;
  width: 60px;
}

.stats-row {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  color: #8c8c8c;
  font-size: 12px;
}

.card-footer {
  display: flex;
  justify-content: space-around;
  padding: 15px;
  border-top: 1px solid #ebeef5;
}

.btn-close {
  color: #f56c6c;
}

.btn-open {
  color: #67c23a;
}

.list-view {
  padding: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.map-container {
  height: 400px;
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.map-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.map-image {
  max-width: 100%;
  height: auto;
  margin-top: 20px;
}
</style>
